package com.example.fx.fg

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.example.base.mvvm.BaseFragment
import com.example.fx.R
import com.example.fx.databinding.FragmentMineBinding
import com.example.fx.fgViewModel.MineViewModel
import com.example.fx.utils.GlideUtils
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector

class MineFragment : BaseFragment<MineViewModel,FragmentMineBinding>() {
    override fun getLayout(): Int  = R.layout.fragment_mine

    override fun getViewModel(): Class<MineViewModel>  = MineViewModel::class.java

    override fun initView() {
       val navHostFragment = childFragmentManager.findFragmentById(R.id.fragmentContainerView2) as NavHostFragment
        val controller = navHostFragment.navController
        binding.bnv.setupWithNavController(controller)

        viewModel.userInfo()
        //点击退出登录按钮
        binding.logout.setOnClickListener {
            activity?.finish()//当前页面退出
            SPUtils.getInstance().clear()//清空SP保存记录
            ARouter.getInstance().build("/app/LoginActivity").navigation()//跳转到登录界面
        }
        //点击修改地址
        binding.userAddress.setOnClickListener {
            val addressPicker = AddressPicker(requireActivity())//地址弹出框
           addressPicker.setTitle("请选择配送地址")
            addressPicker.setAddressMode(AddressMode.PROVINCE_CITY_COUNTY)
            addressPicker.setOnAddressPickedListener { province, city, county ->
                binding.userAddress.text = "${province.name}${city.name}${county.name}"
            }
            addressPicker.show()
        }
        //修改头像
        binding.userImage.setOnClickListener {
            PictureSelector.create(this,102).selectPicture()
        }
    }

    override fun initData() {
        viewModel.success.observe(this){
            if(it.code==200){
                context?.let { it1 -> GlideUtils.loadCircleImage(it1,it.data.avatar,binding.userImage) }
                binding.userName.text = it.data.phone
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==102&&resultCode==Activity.RESULT_OK){
            val pictureBean = data?.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
            context?.let { GlideUtils.loadCircleImage(it,pictureBean.path,binding.userImage) }
        }
    }

}